#include "clientdialog.h"
#include "ui_clientdialog.h"

ClientDialog::ClientDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::ClientDialog)
    , status(false)
{
    ui->setupUi(this);

    connect(&tcpSocket, SIGNAL(connected()), this, SLOT(onConnected()));
    connect(&tcpSocket, SIGNAL(disconnected()), this, SLOT(onDisconnected()));
    connect(&tcpSocket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
    connect(&tcpSocket, SIGNAL(errorOccurred(QAbstractSocket::SocketError)), this, SLOT(onError()));
}

ClientDialog::~ClientDialog()
{
    delete ui;
}

void ClientDialog::on_sendButton_clicked()
{
    // 获取用户要发送的消息
    QString msg = ui->MessageEdit->text();
    if(msg == "")
        return;
    msg = username + ":" + msg;
    // 发送
    tcpSocket.write(msg.toUtf8());
    // 清空消息输入框
    ui->MessageEdit->clear();
}

void ClientDialog::on_connectButton_clicked()
{
    // 如果是未连接，则连接
    if(status == false)
    {
        serverIP.setAddress(ui->serverIPEdit->text());
        serverPort = ui->serverPortEdit->text().toUShort();
        username = ui->usernameEdit->text();
        // 向服务器发起连接
        // 成功发送信号：connected
        // 失败发送信号：error
        tcpSocket.connectToHost(serverIP, serverPort);
    }
    else
    {
        // 如果是已连接，则断开连接
        // 向服务器发送离开聊天室的提示消息
        QString str = username + " : 离开聊天室";
        // toUtf8(): 将QString转换为QByteArray
        tcpSocket.write(str.toUtf8());

        // 和服务器断开连接，也会发送信号disconnect()
        tcpSocket.disconnectFromHost();
    }
}

void ClientDialog::onConnected()
{
    // 连接成功则发送信号：connected
    status = true;
    ui->sendButton->setEnabled(true);   // 恢复发送按钮
    ui->serverIPEdit->setEnabled(false);
    ui->serverPortEdit->setEnabled(false);
    ui->usernameEdit->setEnabled(false);
    ui->connectButton->setText("离开聊天室");

    // 向服务器发送进入聊天室的提示消息
    QString str = username + " : 进入聊天室";
    // toUtf8(): 将QString转换为QByteArray
    tcpSocket.write(str.toUtf8());
}

void ClientDialog::onDisconnected()
{
    status = false;
    ui->sendButton->setEnabled(false);   // 禁用发送按钮
    ui->serverIPEdit->setEnabled(true);
    ui->serverPortEdit->setEnabled(true);
    ui->usernameEdit->setEnabled(true);
    ui->connectButton->setText("连接服务器");

    // 向服务器发送离开聊天室的提示消息
    QString str = username + " : 离开聊天室";
    // toUtf8(): 将QString转换为QByteArray
    tcpSocket.write(str.toUtf8());
}

void ClientDialog::onReadyRead()
{
    if(tcpSocket.bytesAvailable())
    {
        // 接收消息
        QByteArray buf = tcpSocket.readAll();

        // 显示消息
        ui->listWidget->addItem(buf);
        ui->listWidget->scrollToBottom();
    }
}

void ClientDialog::onError()
{
    // errorString()：获取异常原因
    QMessageBox::critical(this, "Error", tcpSocket.errorString());
}

